﻿
Partial Class WebForm_ManageManualUpdate
    Inherits System.Web.UI.Page


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack() Then
            Me.BindDDLReports()
            Me.BindDDLDivision()
            Me.BindGV()
        End If
    End Sub

    Protected Sub ddlReports_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlReports.SelectedIndexChanged
        Select Case ddlReports.SelectedValue
            Case "StockAndPrice"
                Me.chkAutoFill.Visible = True
            Case "FMQty"
                Me.lblDivision.Visible = True
                Me.ddlDivision.Visible = True
            Case Else
                Me.chkAutoFill.Visible = False
                Me.lblDivision.Visible = False
                Me.ddlDivision.Visible = False
        End Select
    End Sub

    Protected Sub gv_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gv.PageIndexChanging
        Me.gv.PageIndex = e.NewPageIndex
        Me.BindGV()
    End Sub

    Protected Sub btnGetFiles_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGetFiles.Click
        Dim sql As New MyStringBuilder
        Dim dat As New clsData
        Try
            '先執行複製最新檔案的排程
            Dim sqlParams As SqlParameter() = New SqlParameter(0) {}
            sqlParams(0) = New SqlParameter("@job_name", SqlDbType.NVarChar)
            sqlParams(0).Value = "BLS_GetLatestSapFile"
            sql.Length = 0
            sql.AppendFormat("[msdb].[dbo].[sp_start_job]")
            '若不執行搬檔案的排程，則須註解下一行程式dat.AccData，其中BTLALL的路徑是設定在資料庫的dbo.EDI資料表內
            dat.AccData(sql.ToString(), sqlParams, CommandType.StoredProcedure)
            MyObj.ShowMessage("Copy files done!!")
        Catch ex As Exception
            MyObj.WriteLog(ex.ToString())
            MyObj.ShowMessage("Copy files error!!")
            Return
        End Try
        '先停60秒,等檔案複製完
        Threading.Thread.Sleep(60000)
    End Sub

    Protected Sub btReports_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btReports.Click
        Dim sql As New MyStringBuilder
        Dim dat As New clsData
        Dim Success As Boolean
        Dim ErrorMessage As String = ""
        Dim SuccessMessage As String = "Successful"
        Try
            sql.Length = 0
            Select Case ddlReports.SelectedValue
                Case "BOMMaster"
                    sql.AppendFormat("exec ImportBOMMaster ")

                Case "CustomerMaster"
                    sql.AppendFormat("exec ImportCustomerMaster ")

                Case "FinancialPLInformation"
                    sql.AppendFormat("exec ImportFinancialPLInformation ")

                Case "FMDSellOut"
                    sql.AppendFormat("exec GetSellOutDataFromMARS 'LPD','{0}','{1}' ", DateTime.Now.ToString("yyyyMMdd"), "D")

                Case "FMDStock"
                    sql.AppendFormat("exec GetTradeStockDataFromMARS 'LPD','{0}' ", DateTime.Now.ToString("yyyyMMdd"))

                Case "FMHSellOut"
                    sql.AppendFormat("exec GetSellOutDataFromMARS 'LPD','{0}','{1}' ", DateTime.Now.AddMonths(-1).ToString("yyyyMMdd"), "M")

                Case "FMQty"
                    sql.AppendFormat("exec GetFMQty 'TW_{0}' ", Me.ddlDivision.SelectedValue)
                    SuccessMessage &= "(" & Me.ddlDivision.SelectedValue & ")"

                Case "ItemMaster"
                    sql.AppendFormat("exec ImportItemMaster ")

                Case "PLVQty"
                    sql.AppendFormat("exec ImportPLVQty ")

                Case "ProductHierarchyMaster"
                    sql.AppendFormat("exec ImportProductHierarchyMaster ")

                Case "ProductPOSCounter"
                    sql.AppendFormat("exec ImportProductPOSCounter ")

                Case "SellIn"
                    sql.AppendFormat("exec ImportSellInInformation ")

                    'Case "SellOut"
                    'sql.AppendFormat("exec ImportSellOutInformation ")

                Case "StockAndPrice"
                    sql.AppendFormat("exec ImportStockAndPrice ")
                    If Me.chkAutoFill.Checked = True Then
                        sql.AppendFormat(";exec RollingListPSTD '{0}' ", DateTime.Now.ToString("yyyyMM"))
                    End If

                Case "StockAndPricePeriod"
                    sql.AppendFormat("exec ImportStockAndPricePeriod ")
                    'Case "TradeStock"
                    'sql.AppendFormat("exec ImportTradeStockInformation ")
            End Select

            'MyObj.WriteLog(sql.ToString())

            If sql.Length = 0 Then
                Success = False
                ErrorMessage = "Unsuccessful"
            Else
                dat.AccData(sql)
                Success = True
            End If
        Catch ex As SqlException
            'MyObj.WriteLog(ex.ToString())
            Success = False
            If ex.Message.Contains("Timeout") OrElse ex.Message.Contains("逾時") Then
                ErrorMessage = "Time Out"
            ElseIf ex.Message.Contains("Format Error") OrElse ex.Message.Contains("格式錯誤") OrElse ex.Message.Contains("轉換錯誤") OrElse ex.Message.Contains("could not be open") Then
                ErrorMessage = "Format Error"
            ElseIf ex.Message.Contains("Data Empty") OrElse ex.Message.Contains("不存在") Then
                ErrorMessage = "Data Empty"
            Else
                Throw
            End If


            'Select Case ex.ErrorCode

            '    Case ""
            '        MessageItem = "Time Out"
            '    Case ""
            '        MessageItem = "Format Error"
            'End Select
        End Try
        sql.Length = 0
        sql.AppendFormat("Insert into ManualUpdateRecord(EDIDescription,UpdateResult,UpdateBy,UpdateDate) ")
        sql.AppendFormat("select ")
        sql.AppendFormat("'{0}', ", ddlReports.SelectedValue)
        sql.AppendFormat("'{0}', ", IIf(Success, SuccessMessage, ErrorMessage))
        sql.AppendFormat("'{0}', ", clsAuth.GetUserID())
        sql.AppendFormat("{0} ", "getdate()")

        dat.AccData(sql)
        Me.BindGV()

    End Sub


    Protected Sub BindDDLReports()
       
        ddlReports.DataTextField = "LongDescription"
        ddlReports.DataValueField = "EDIDescription"
        Dim sql As New MyStringBuilder
        Dim dat As New clsData
        sql.AppendFormat("Select * from EDI where ShowInReport='Y' ")

        ddlReports.DataSource = dat.GetData(sql)
        ddlReports.DataBind()
        ddlReports.Items.Insert(0, MyObj.GetDDLPleaseChooseItem())
    End Sub

    Private Sub BindDDLDivision()
        Dim ddlControl As DropDownList = Me.ddlDivision
        Dim dvManager As New DivisionManager

        ddlControl.DataTextField = "Division"
        ddlControl.DataValueField = "Division"
        ddlControl.DataSource = dvManager.GetAllDivision()
        ddlControl.DataBind()
    End Sub

    Protected Sub BindGV()
        Dim sql As New MyStringBuilder
        Dim dat As New clsData

        sql.AppendFormat("select mdr.UpdateBy,convert(varchar(10),mdr.UpdateDate,111) as UpdateDate,convert(varchar(10),UpdateDate,108) as UpdateTime ,e.LongDescription ,mdr.UpdateResult from ManualUpdateRecord mdr ")
        sql.AppendFormat("left join EDI e on mdr.EDIDescription = e.EDIDescription ")
        sql.AppendFormat("order by mdr.UpdateDate desc ")


        gv.DataSource = dat.GetData(sql)
        gv.DataBind()

    End Sub




End Class
